package com.leyou.gateway;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 是否要执行run方法
     * @return true：执行run方法，false：不执行run方法，直接放行
     */
    @Override
    public boolean shouldFilter() {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request
        HttpServletRequest request = ctx.getRequest();
        // 判断是否放行
        boolean isAllow = isAllowRequest(request);

        // 如果是需要放行的，这里要返回false，否则返回true
        return !isAllow;
    }

    private boolean isAllowRequest(HttpServletRequest request) {
        // 1.获取请求路径
        String path = request.getRequestURI();
        // 2.获取请求方法
        String method = request.getMethod();
        // 3.判断
        for (Map.Entry<String,String> entry: filterProp.getAllowPathMap().entrySet()) {
            // 取出path
            String allowPath = entry.getKey();
            // 取出method
            String allowMethod = entry.getValue();

            if(path.startsWith(allowPath) && ("*".equals(allowMethod) || allowMethod.equalsIgnoreCase(method))){
                return true;
            }
        }
        return false;
    }

    /**
     * 拦截的逻辑
     */
    @Override
    public Object run() throws ZuulException {
        // 获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 1.获取用户的登录凭证jwt
            String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());

            // 2.解析jwt，获取用户身份
            Payload<UserInfo> payload = null;
            // 2.1.如果解析失败，证明没有登录，返回401
            try {
                payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            } catch (Exception e) {
                throw new RuntimeException("token校验失败！");
            }
            // 2.2.如果解析成功，继续向下，校验token黑名单
            Boolean isExists = redisTemplate.hasKey(payload.getId());
            if(BooleanUtils.isTrue(isExists)){
                throw new RuntimeException("token已经失效！");
            }
            // 3.根据身份，查询用户权限信息
            String username = payload.getUserInfo().getUsername();
            String role = payload.getUserInfo().getRole();

            // 4.获取当前请求资源（微服务接口路径）
            String path = request.getRequestURI();

            // TODO 5.判断是否有访问资源的权限
            log.info("用户{}, 角色{}, 正在访问{} 资源", username, role, path);

        } catch (RuntimeException e) {
            log.error("用户token校验失败，原因：{}", e.getMessage());
            // 拦截请求
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(403);
        }
        return null;
    }
}
